package au.edu.unsw.editingtool.global;

import java.sql.SQLException;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSession;

import au.edu.unsw.editingtool.db.DBEditingpool;
import au.edu.unsw.editingtool.db.DBSession;

public class SessionBindingListener implements HttpSessionBindingListener {
	 // Save a ServletContext to be used for its log() method
	  String ServletContext;
	  String currentSessionid;
	  String currentUsername;
	  String currentSid;
	  
	public SessionBindingListener(String context, String username, String sessionid, String sid) {
		ServletContext = context;
		currentSessionid = sessionid;
		currentSid = sid;
		currentUsername = username;
	}
	public void valueBound(HttpSessionBindingEvent event) {		
		System.out.println("[SESSIONBINDINGLISTENER] Session BOUND!");
	}

	public void valueUnbound(HttpSessionBindingEvent event) {
		
		System.out.println("[SESSIONBINDINGLISTENER] Session UNBOUND!");
		DBEditingpool dbeditingpool = new DBEditingpool();
		dbeditingpool.setConfFile(ServletContext + GlobalConstant.configFilePath);
		DBSession dbsession = new DBSession();
		dbsession.setConfFile(ServletContext + GlobalConstant.configFilePath);
		
		
		try {
			if(currentSessionid!=null &&currentUsername!=null)
			{
				System.out.println("[SESSIONBINDINGLISTENER] Delete editingpool for username="+currentUsername+" with sessionid="+currentSessionid);
				dbeditingpool.deleteRecord(currentUsername, currentSessionid);
			}
			if(currentSessionid!=null && currentSid!=null && currentUsername!=null)
			{
				System.out.println("[SESSIONBINDINGLISTENER] Delete dbsession for username="+currentUsername+" with sid="+currentSid+" and sessionid="+currentSessionid);
				dbsession.deleteSession(currentSid, currentSessionid, currentUsername);
			}
		} catch (Exception e) {	
			System.out.println("[SESSIONBINDINGLISTENER] FAILED to delete data on editingpool and session tables!");
			e.printStackTrace();
		}		
	}
	public void setUsername(String username)
	{
		currentUsername = username;
	}
	public void setSessionId(String sessionid)
	{
		currentSessionid = sessionid;
	}
	public void setSid(String sid)
	{
		currentSid = sid;
	}
}
